#include<iostream>
#include<pthread.h>
#include<cstdlib>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<cstring>

const int port=8081;
const int num=5;

void* Routinue(void* arg)
{
  pthread_detach(pthread_self());//线程分离
  int fd=*(int*)arg;
  delete (int*)arg;

  std::cout<<"get a new link fd:"<<fd<<std::endl;

  return nullptr;
}

int main()
{
  //创建监听套接字
  int lsock=socket(AF_INET,SOCK_STREAM,0);
  if(lsock<0)
  {
    //创建套接字失败
    std::cerr<<"socket error"<<std::endl;
    return 1;
  }

  //本地
  struct sockaddr_in local;
  memset(&local,0,sizeof(local));
  local.sin_family=AF_INET;
  local.sin_port=htons(port);
  local.sin_addr.s_addr=INADDR_ANY;
  
  //绑定
  if(bind(lsock,(struct sockaddr*)&local,sizeof(local))<0)
  {
    //绑定失败
    std::cerr<<"bind error"<<std::endl;
    return 2l;
  }

  //监听
  if(listen(lsock,num)<0)
  {
    //监听失败
    std::cerr<<"listen error"<<std::endl;
    return 3;
  }

  //远端
  struct sockaddr_in peer;
  for(;;)
  {
    socklen_t len=sizeof(peer);
    int sock = accept(lsock,(struct sockaddr*)&peer,&len);
    if(sock<0)
    {
      //接收失败
      std::cerr<<"accept error"<<std::endl;
      continue;
    }

    //使用多线程处理
    int* p=new int(sock);
    pthread_t tid;
    pthread_create(&tid,nullptr,Routinue,p);
  }

  return 0;
}
